<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Goods\Repository;

use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Query\Expr\Join;
use Goods\Entity\Goods;
use Goods\Entity\GoodsGroupPrice;
use Goods\Entity\GoodsImage;
use Goods\Entity\GoodsOtherTagGoods;
use Goods\Entity\GoodsSalesRecord;

class GoodsOtherTagGoodsRepository extends EntityRepository
{
    /**
     * 后台，聚合标签商品列表
     * @param $otherTagId
     * @return float|int|mixed|string
     */
    public function findOtherTagGoodsList($otherTagId)
    {
        $query = $this->getEntityManager()->createQueryBuilder();
        $query->select('ot', 'g.goodsName', 'g.goodsState')
            ->from(GoodsOtherTagGoods::class, 'ot')
            ->innerJoin(Goods::class, 'g', Join::WITH, 'ot.goodsId=g.goodsId')
            ->where('ot.otherTagId = :otherTagId')->setParameter('otherTagId', $otherTagId)
            ->orderBy('ot.otherTagGoodsSort', 'ASC');

        return $query->getQuery()->getResult();
    }

    /*==============================================下面为前台调用==============================================*/

    /**
     * 聚合标签商品列表
     * @param $otherTagId
     * @param $userGroupId
     * @return float|int|mixed|string
     */
    public function shopFindOtherTagGoodsList($otherTagId, $userGroupId)
    {
        $query = $this->getEntityManager()->createQueryBuilder();
        $query->select('ot',
            'g.goodsName', 'g.goodsExtendName', 'g.virtualSales', 'g.classId', 'g.goodsPrice', 'g.goodsMarketPrice', 'g.goodsWeight', 'g.goodsWeightUnit',
            'i.goodsThumbnailImage',
            'r.goodsSalesNum'
            )
            ->from(GoodsOtherTagGoods::class, 'ot')
            ->innerJoin(Goods::class, 'g', Join::WITH, 'g.goodsId = ot.goodsId')
            ->innerJoin(GoodsSalesRecord::class, 'r', Join::WITH, 'g.goodsId =  r.goodsId')
            ->leftJoin(GoodsImage::class, 'i', Join::WITH, 'g.goodsImageId = i.goodsImageId')
            ->where('ot.otherTagId = :otherTagId')->setParameter('otherTagId', $otherTagId)
            ->andWhere('g.goodsState=1')
            ->orderBy('ot.otherTagGoodsSort', 'ASC');

        //如果会员组存在，则获取会员组价格
        if($userGroupId > 0) $query->addSelect('(SELECT p.userGroupPrice FROM '.GoodsGroupPrice::class.' AS p WHERE p.goodsId=g.goodsId AND p.userGroupId='.$userGroupId.') AS goodsGroupPrice');

        return $query->getQuery()->getResult();
    }
}